const { fetchArtworks } = require("../../../utils/request");
const config = require("../../../utils/config");

Page({
    data: {
      artworks:[],  //艺术作品列表数据
      artistId: null,
      artistName: '',
      pageNum: 1, // 当前页数
      pageSize: 10, // 每页显示的条数
      isLoading: false, // 是否正在加载数据
      hasMore: true, // 是否还有更多数据
    },
  
    onLoad(options) {
      if (options.artistId) {
        this.setData({
          artistId: options.artistId,
          artistName: options.artistName
        });
        this.loadArtworks(options.artistId);
      }
        // const artistId = 1;
        // const artistName = "XXXYYYZZZ";
        // this.setData({
        //   artistId: artistId,
        //   artistName: artistName
        // });
        // this.loadArtworks(artistId);
    },

    onReachBottom() {
        // 当页面滚动到底部时触发
        if (this.data.hasMore && !this.data.isLoading) {
            this.loadMoreArtworks();
        }
    },
  
    async loadArtworks(artistId) {
        this.setData({ isLoading: true });
        const { pageNum, pageSize } = this.data;
        fetchArtworks({ artistId, pageNum, pageSize }).then(res => {
            if (res.code === '00000' && res.data && res.data.list) {
              const updatedArtworks = res.data.list.map((artwork) => ({
                ...artwork,
                primaryImageSmallUrl: `${config.ImageURL}${artwork.primaryImageSmallUrl}`,
              }));
              // this.setData({ artworks: [...this.data.artworks, ...updatedArtworks] });
              this.setData({ 
                artworks: [...this.data.artworks, ...updatedArtworks],
                hasMore: updatedArtworks.length >= this.data.pageSize
               });
            } else {
                wx.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
        }).finally(() => {
            this.setData({ isLoading: false });
        });
    },

    async loadMoreArtworks() {
        const { artistId, pageNum } = this.data;
        this.setData({ pageNum: pageNum + 1 });
        this.loadArtworks(artistId);
    },

  });
  